import { Component, OnInit } from '@angular/core';
import { FetchService } from '../../../../core/net/fetch.service';
import { DataReportService } from '../../data-report.service';
import * as _ from 'lodash';
import * as moment from 'moment';
import { HttpClient } from '@angular/common/http';

@Component({
    selector: 'app-wt-irrigate',
    templateUrl: './wt-irrigate.component.html',
    styleUrls: ['./wt-irrigate.component.scss', '../water-takes-report.component.scss']
})
export class WtIrrigateComponent implements OnInit {
    // irrigateType = '1'; //  1-夏秋灌 2冬灌
    listData = [];

    contentTitle: string;
    frId: string;
    today: Date = new Date();
    datePicker: Date = new Date();
    range: Date[];
    // quickTimeSelect = null;
    tableData = [];
    scrollConfig = {
        x: '1200px',
    };
    summerHead = [];
    irrHistoryData = [];
    modalTableData = [];
    modalSummerHead = [];

    basicOpts: any = {
        title: {
            text: '',
            x: 'center',
            textStyle: {
                color: '#777',
                fontSize: 16
            }
        },
        color: ['#3398DB', '#ddb00a'],
        grid: {
            top: '10%',
            left: '3%',
            right: '4%',
            bottom: '8%',
            containLabel: true
        },
        tooltip: {
            trigger: 'axis'
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: []
        },
        yAxis: {
            type: 'value'
        }
    };
    irrChartOpts: any = {};
    usageChartOpts: any = {};
    modalTitle: string = '灌溉进度历史数据';
    modalShow: boolean = false;
    progressModalShow: boolean = false;
    progressData = [];
    reportFinished = 0;
    reportUnfinished = 0;
    reportPercentage = 0;

    currId: string;

    constructor(private fetchService: FetchService,
                private http: HttpClient,
                private dataReportService: DataReportService) {
    }

    ngOnInit() {
        // this.irrigateType = this.dataReportService.irrigateType(this.today);
        // this.irrigateType = '1';
        this.fetchService.post<any>('muw/wrsMuwFr/list', {type: '2'}).subscribe(res => {
            this.listData = res;
            this.selectedAreaChanged(this.listData[0].id);
            this.currId = this.listData[0].id;
        });
        this.getProgressData();
    }

    getProgressData(): void {
        this.fetchService.post<any>('muw/submit/querySubmitIrr', {}).subscribe(res => {
            if (res) {
                const group = _.groupBy(res, 'statu');
                this.reportFinished = group['2'] ? group['2'].length : 0;
                this.reportUnfinished = group['1'] ? group['1'].length : 0;
                this.reportPercentage = res.length === 0 ? 0 : Math.round(this.reportFinished / res.length * 100);
                res.forEach(item => {
                    item['status'] = item.statu === 1 ? '未报送' : '已报送';
                });
                this.progressData = _.sortBy(res, o => {
                    return o.statu;
                });
            }
        });
    }

    openProgressModal(): void {
        this.progressModalShow = true;
    }

    closeProgressModal() {
        this.progressModalShow = false;
    }

    selectedAreaChanged(id): void {
        this.currId = id;
        const selectedArea = _.find(this.listData, item => {
            return item.id === id;
        });
        this.contentTitle = selectedArea.name;
        this.frId = id;
        // const params = {
        //     frId: id,
        //     type: this.irrigateType,
        //     date: moment(this.today).valueOf()
        // };
        // this.fetchService.post<any>('muw/wrsMuwIrrData/list', params).subscribe(res => {
        //     // if (this.irrigateType === '1') {
        //     this.summerHead = res.datas[0].irrDatas.map(o => {
        //         return {
        //             name: o.trIrrName,
        //             dailyName: `${o.trIrrName}_daily`,
        //             accName: `${o.trIrrName}_acc`,
        //             plan: `${o.trIrrName}_plan`,
        //             percentage: `${o.trIrrName}_percentage`
        //         };
        //     });
        //     res.datas.forEach(item => {
        //         this.summerHead.forEach(props => {
        //             const obj = _.find(item.irrDatas, food => {
        //                 return food.trIrrName === props.name;
        //             });
        //             item[props.dailyName] = obj.val;
        //             item[props.accName] = obj.valTotal;
        //             item[props.plan] = obj.planValTotal;
        //             item[props.percentage] = obj.planPer;
        //         });
        //     });
        //     this.tableData = res.datas;
        //     // } else if (this.irrigateType === '2') {
        //     //
        //     // }
        // });
        this.onDateChanged(this.today);
    }

    onDateChanged(date): void {
        // this.irrigateType = this.dataReportService.irrigateType(date);
        const params = {
            frId: this.frId,
            // type: this.irrigateType,
            date: moment(date).valueOf()
        };
        this.fetchService.post<any>('muw/wrsMuwIrrData/list', params).subscribe(res => {
            this.summerHead = res.datas[0].irrDatas.map(o => {
                return {
                    name: o.trIrrName,
                    dailyName: `${o.trIrrName}_daily`,
                    accName: `${o.trIrrName}_acc`,
                    plan: `${o.trIrrName}_plan`,
                    percentage: `${o.trIrrName}_percentage`
                };
            });
            res.datas.forEach(item => {
                this.summerHead.forEach(props => {
                    const obj = _.find(item.irrDatas, food => {
                        return food.trIrrName === props.name;
                    });
                    const percentage = typeof obj.planPer === 'number' ? (parseFloat(obj.planPer) * 100).toFixed(2) + '%' : obj.planPer;

                    item[props.dailyName] = obj.val;
                    item[props.accName] = obj.valTotal;
                    item[props.plan] = obj.planValTotal;
                    item[props.percentage] = percentage ;
                });
            });
            this.tableData = res.datas;
            this.getChartsData();
        });
    }

    getChartsData(): void {
        const params = {
            frId: this.frId,
            // type: this.irrigateType,
            startDate: moment(this.today).subtract(15, 'days').valueOf(),
            endDate: moment(this.today).valueOf()
        };
        this.fetchService.post<any>('muw/wrsMuwIrrData/historyDataList', params).subscribe(res => {
            res.forEach(data => {
                data.date = moment(data.time).format('YYYY-MM-DD');
            });
            this.irrHistoryData = res;
            const xAxisArr = this.irrHistoryData.map(item => {
                return item.date;
            });
            const legendArr = [];
            this.summerHead.forEach(item => {
                if (item.name !== '用水量') {
                    legendArr.push(item.name);
                }
            });
            const commonOpts = {
                legend: {
                    bottom: '4%',
                    data: legendArr
                },
                grid: {
                    top: '10%',
                    left: '8%',
                    right: '8%',
                    bottom: '12%',
                    containLabel: true
                },
                xAxis: {
                    data: xAxisArr
                },
                color: ['#1ada6f', '#ffbf44', '#12d0d2', '#0092f1', '#ffdc00', '#f9383b']
            };
            // if (this.irrigateType === '1') {
            const irrSeriesData = legendArr.map(irrName => {
                const seriesData = [];
                this.irrHistoryData.forEach(results => {
                    let areaTotal = 0;
                    results.datas.forEach(item => {
                        const obj = _.find(item.irrDatas, food => {
                            return food.trIrrName === irrName;
                        });
                        if (obj) {
                            areaTotal += obj.val;
                        }
                    });
                    seriesData.push(areaTotal);
                });
                return {
                    name: irrName,
                    type: 'line',
                    stack: '总量',
                    data: seriesData
                };
            });
            this.irrChartOpts = {
                ...commonOpts, ...{
                    title: {
                        text: `${this.contentTitle}灌溉进度总计`
                    },
                    yAxis: {
                        name: '灌溉进度(亩)'
                    },
                    series: irrSeriesData
                }
            };
            // const usageSeriesData = [];
            // this.irrHistoryData.forEach(results => {
            //     let areaTotal = 0;
            //     results.datas.forEach(item => {
            //         const obj = _.find(item.irrDatas, food => {
            //             return food.trIrrName === '用水量';
            //         });
            //         if (obj) {
            //             areaTotal += obj.val;
            //         }
            //     });
            //     usageSeriesData.push(areaTotal);
            // });
            // this.usageChartOpts = {
            //     ...commonOpts, ...{
            //         title: {
            //             text: `${this.contentTitle}用水量总计`
            //         },
            //         yAxis: {
            //             name: '用水量(万m³)'
            //         },
            //         color: ['#058e04'],
            //         series: usageSeriesData
            //     }
            // };
            // } else {
            //     const dailySeriesData = [];
            //     const accumulation = [];
            //     this.irrHistoryData.forEach(results => {
            //         // let areaTotal = 0;
            //         let acc = 0;
            //         results.datas.forEach(item => {
            //             // const obj = _.find(item.irrDatas, food => {
            //             //     return food.trIrrName === '用水量';
            //             // });
            //             const accObj = _.find(item.irrDatas, food => {
            //                 return food.trIrrName === '灌溉进度';
            //             });
            //             // if (obj) {
            //             //     areaTotal += obj.val;
            //             //     acc += obj.valTotal;
            //             // }
            //             if (accObj) { acc += obj.val; }
            //         });
            //         // dailySeriesData.push(areaTotal);
            //         accumulation.push(acc);
            //     });
            //     this.irrChartOpts = {
            //         ...commonOpts, ...{
            //             title: {
            //                 text: `${this.contentTitle}灌溉进度总计`
            //             },
            //             yAxis: {
            //                 name: '灌溉面积(万m³)'
            //             },
            //             series: [
            //                 {
            //                     name: '灌溉面积',
            //                     type: 'line',
            //                     data: accumulation
            //                 }
            //             ]
            //         }
            //     };
            //     // this.usageChartOpts = {
            //     //     ...commonOpts, ...{
            //     //         title: {
            //     //             text: `${this.contentTitle}累计用水量`
            //     //         },
            //     //         yAxis: {
            //     //             name: '累计用水量(万m³)'
            //     //         },
            //     //         series: [
            //     //             {
            //     //                 name: '累计用水量',
            //     //                 type: 'line',
            //     //                 data: accumulation
            //     //             }
            //     //         ]
            //     //     }
            //     // };
            // }

        });

    }

    // onRangeChange(result: Date[] | number[]): void {
    //     const start = result[0] ? moment(result[0]).valueOf() : moment().valueOf();
    //     const end = result[1] ? moment(result[1]).valueOf() : moment().valueOf();
    //     const params = {
    //         frId: this.frId,
    //         type: this.irrigateType,
    //         startDate: start,
    //         endDate: end,
    //     };
    //     this.fetchService.post<any>('muw/wrsMuwIrrData/historyDataList', params).subscribe(res => {
    //         res.forEach(data => {
    //             data.date = moment(data.time).format("YYYY-MM-DD");
    //         });
    //         this.irrHistoryData = res;
    //     });
    // }
    //
    // quickSelect(selected: string): void {
    //     const start = moment().subtract(parseInt(selected, 10), 'days').valueOf();
    //     const end = moment().valueOf();
    //     this.onRangeChange([start, end]);
    // }

    openDetailModal(): void {
        this.modalShow = true;
        this.queryInfo(this.today);
    }

    export(): void {
        const param = {
            frId: this.frId ? this.frId : ''
        };
        this.fetchService.export('muw/wrsMuwIrrData/export', param).subscribe((res: any) => {
            const blob = new Blob([res], {type: 'application/vnd.ms-excel    application/x-excel;charset=utf-8'});
            const elink = document.createElement('a');

            elink.download = `${this.contentTitle}灌溉进度表.xlsx`;
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink);
        });
    }

    print(): void {
    }

    onCancel() {
        this.modalShow = false;
    }

    queryInfo(date): void {
        const time = moment(date).valueOf();
        // const historyIrrType = this.dataReportService.irrigateType(time);
        const params = {
            frId: this.frId,
            // type: historyIrrType,
            date: time
        };
        this.fetchService.post<any>('muw/wrsMuwIrrData/list', params).subscribe(res => {
            // if (this.irrigateType === '1') {
            this.modalSummerHead = res.datas[0].irrDatas.map(o => {
                return {
                    name: o.trIrrName,
                    dailyName: `${o.trIrrName}_daily`,
                    accName: `${o.trIrrName}_acc`,
                    plan: `${o.trIrrName}_plan`,
                    percentage: `${o.trIrrName}_percentage`
                };
            });
            res.datas.forEach(item => {
                this.modalSummerHead.forEach(props => {
                    const obj = _.find(item.irrDatas, food => {
                        return food.trIrrName === props.name;
                    });
                    item[props.dailyName] = obj.val;
                    item[props.accName] = obj.valTotal;
                    item[props.plan] = obj.planValTotal;
                    item[props.percentage] = obj.planPer;
                });
            });
            this.modalTableData = res.datas;
        });
        //   const params = {
        //     frId: this.frId,
        //     type: historyIrrType,
        //     startDate: time,
        //     endDate: time,
        //   };
        //   this.fetchService.post<any>('muw/wrsMuwIrrData/historyDataList', params).subscribe(resp => {
        //
        //       const res = resp[0];
        //       this.modalSummerHead = res.datas[0].irrDatas.map(o => {
        //         return {
        //           name: o.trIrrName,
        //           dailyName: `${o.trIrrName}_daily`,
        //           accName: `${o.trIrrName}_acc`
        //         };
        //       });
        //       res.datas.forEach(item => {
        //         this.modalSummerHead.forEach(props => {
        //           const obj = _.find(item.irrDatas, food => {
        //             return food.trIrrName === props.name;
        //           });
        //           item[props.dailyName] = obj.val;
        //           item[props.accName] = obj.valTotal;
        //         });
        //       });
        //       this.modalTableData = res.datas;
        //
        //   });
        // }
    }
}
